<?php
/**
 * 邮件管理
 */
namespace app\controllers;

use app\components\Email;
use app\components\EmailMarket;
use app\models\Elog;
use app\models\marketing\MailSendlist;
use app\models\Template;
use app\models\User;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\EmailSystemEmail;
use yii\db\Query;
use yii\db\Command;
use yii\helpers\Url;
use yii\data\Pagination;
use app\components\smarty\SmartyNewRenderer;
use app\components\TemplateMarket;
use app\models\MailTemplateModel;
use yii\helpers\Html;

class EmailManageController extends \app\base\Controller
{
	public $enableCsrfValidation = false;

	/**
	 * 邮件列表
	 */
	public function actionIndex()
        {
        $data = [];
        $siteInfo = [];

        $defaultPageSize = 20;

        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');

        // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();

       // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();

//        $siteInfo[0] = '网站';
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }

        // 当前用户所有有权限的站点结束
        $formData['siteInfo'] = $siteInfo;
        $formData['site_user_id'] = 0;
        $formData['email'] = '';
        // 用户邮箱
        if(isset($formData['keywords']) && !is_numeric($formData['keywords'])) {
            $emailObj = new Email();
        
            $formData['email'] = $emailObj->encryption(trim($formData['keywords']));
        } else if(isset($formData['keywords']) && is_numeric($formData['keywords'])) {
            
            $formData['site_user_id'] = intval($formData['keywords']);
        }
        
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : array_keys($siteInfo)[0];
        //邮件发送状态
        $formData['status'] = isset($formData['status']) ? $formData['status'] : '';
        // 时间相关
        $formData['startTime'] = isset($formData['startTime']) ? $formData['startTime'] : '';
        $formData['endTime'] = isset($formData['endTime']) ? $formData['endTime'] : '';
        
        
        // 当前时间 
        $curTime = \yii::$app->bjTime->time();
        $timeYearMonthStart = \yii::$app->bjTime->date('Y-m-d',$curTime-30*24*60*60);
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',$curTime);
        $formData['startTime'] = !empty($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = !empty($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;
        
        $formData['templateType'][0] = '全部';
        
        $reg_source = ['ALL'=> '全部'];
        if($formData['site_id']) {
            $flag = Yii::$app->authority->judgeSysEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            // 邮件类型
            $templateModel = new MailTemplateModel;
            $templateTypes = $templateModel->getTemplateType($formData['site_id']);
            foreach($templateTypes as $templateType) {
                $formData['templateType'][$templateType['id']] = $templateType['sys_template_type_description'];
            }
            $reg_source = TemplateMarket::regSourceList($formData['site_id']);
        }
        
        $formData['template_type_id'] = isset($formData['template_type_id']) ? intval($formData['template_type_id']) : 0;
        $formData['reg_source'] = isset($formData['reg_source']) ? trim($formData['reg_source']) : 'ALL';
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        $model = new EmailSystemEmail();
        // 导出数据
        if(isset($formData['downLoad']) && $formData['downLoad']) {
                $data = $model->downLoadEmailList($formData);
                if($data['code'] != 0) {
                    $this->sysMsg('警告',$data['msg'],$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                }
                return;
        } else {
            
            $email_data = $model->getEmailList( $formData);

            // 分页相关
            $totalCount = $email_data['totalCount'];
            $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
            $pageCount = $pages->getPageCount(); //页数

            $pageOther = ['totalCount' => $totalCount, 'pageCount' => $pageCount];

            // echo "<pre>";
            // print_r($formData);
            // 渲染模版
            return $this->render('list',[
                'data' => $email_data['email_info'],
                'site' => $site,
                'pages' => $pages,
                'reg_source' => $reg_source,
                // // 'pageOther' => $pageOther,
                'formData' => $formData,
                // // 'curPageIds' => $curPageIds,
            ]);
        }
    }

    /**
	 * 邮件列表
	 */
	public function actionNewIndex()
        {
        $data = [];
        $siteInfo = [];

        $defaultPageSize = 20;

        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');

        // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();

       // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getSysEmailAccessSite();

//        $siteInfo[0] = '网站';
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }

        // 当前用户所有有权限的站点结束
        $formData['siteInfo'] = $siteInfo;
        $formData['site_user_id'] = 0;
        $formData['email'] = '';
        // 用户邮箱
        if(isset($formData['keywords']) && !is_numeric($formData['keywords'])) {
            $emailObj = new Email();
        
            $formData['email'] = $emailObj->encryption(trim($formData['keywords']));
        } else if(isset($formData['keywords']) && is_numeric($formData['keywords'])) {
            
            $formData['site_user_id'] = intval($formData['keywords']);
        }
        
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : array_keys($siteInfo)[0];
        //邮件发送状态
        $formData['status'] = isset($formData['status']) ? $formData['status'] : '';
        // 时间相关
        $formData['startTime'] = isset($formData['startTime']) ? $formData['startTime'] : '';
        $formData['endTime'] = isset($formData['endTime']) ? $formData['endTime'] : '';
        
        
        // 当前时间 
        $curTime = \yii::$app->bjTime->time();
        $timeYearMonthStart = \yii::$app->bjTime->date('Y-m-d',$curTime-30*24*60*60);
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',$curTime);
        $formData['startTime'] = !empty($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = !empty($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;
        
        $formData['templateType'][0] = '全部';
        
        $reg_source = ['ALL'=> '全部'];
        if($formData['site_id']) {
            $flag = Yii::$app->authority->judgeSysEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            // 邮件类型
            $templateModel = new MailTemplateModel;
            $templateDatas = $templateModel->newGetTemplateType($formData['site_id']);
            
            $templateInfo = [];
            foreach($templateDatas as $templateData) {
                $formData['templateType'][$templateData['id']] = $templateData['name'];
                $templateInfo[$templateData['id']] = ['name' => $templateData['name'], 'uuqid' => $templateData['uuqid']];
            }
            
            $reg_source = TemplateMarket::regSourceList($formData['site_id']);
        }
        
        $formData['template_id'] = isset($formData['template_id']) ? intval($formData['template_id']) : 0;
        $formData['reg_source'] = isset($formData['reg_source']) ? trim($formData['reg_source']) : 'ALL';
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        $model = new EmailSystemEmail();
        // 导出数据
        if(isset($formData['downLoad']) && $formData['downLoad']) {
                $data = $model->newDownLoadEmailList($formData, $templateInfo);
                if($data['code'] != 0) {
                    $this->sysMsg('警告',$data['msg'],$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                }
                return;
        } else {
            
            $email_data = $model->newGetEmailList($formData);

            // 分页相关
            $totalCount = $email_data['totalCount'];
            $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
            $pageCount = $pages->getPageCount(); //页数

            $pageOther = ['totalCount' => $totalCount, 'pageCount' => $pageCount];

            // echo "<pre>";
            // print_r($formData);
            // 渲染模版
            return $this->render('new-list',[
                'data' => $email_data['email_info'],
                'site' => $site,
                'pages' => $pages,
                'templateInfo' => $templateInfo,
                'reg_source' => $reg_source,
                // // 'pageOther' => $pageOther,
                'formData' => $formData,
                // // 'curPageIds' => $curPageIds,
            ]);
        }
    }

    
    
    /*
     * 异步获取网站对应的所有邮件类型
     */
    public function actionGetTemplateTypeBySiteid()
    {
        $site_id = intval(Yii::$app->request->get('site_id'));
        $reg_source = trim(Yii::$app->request->get('reg_source'));
        $return[0] = '全部'; 
        if($site_id) {
            $templateModel = new MailTemplateModel;
            $templateTypes = $templateModel->getTemplateType($site_id, $reg_source);
            foreach($templateTypes as $templateType) {
                $return[$templateType['id']] = $templateType['sys_template_type_description'];
            }
        }
        $datas = Html::dropDownList('template_type_id',0,$return, ['class' => 'form-control input-sm mr10 mb5']);
        return json_encode(['status' => 1,'datas' => $datas]);
    }

	/**
	 * 邮件详情
	 * 
	 */
	public function actionTemplateDetail()
    {

        $method = strtolower(Yii::$app->request->getMethod());

        $requestData = Yii::$app->request->$method();
        $site = isset( $requestData['site']) ? $requestData['site'] : '';
        $template_id = isset( $requestData['tid']) ? $requestData['tid'] : 0;
        $id = isset( $requestData['id']) ? intval($requestData['id']) : 0;
        $site_id = isset( $requestData['site_id']) ? $requestData['site_id'] : 0;
        $template_identify = isset( $requestData['identify']) ? $requestData['identify'] : 0;
        if ( $template_id != 0 ) {
            $sql = " SELECT * FROM template WHERE id = " . $template_id;
        } else {
            $sql = " SELECT * FROM template WHERE site_id = " . $site_id ." AND identify = " . $template_identify . " AND state = 1";
        }
        $templateInfo = Yii::$app->db->createCommand($sql)->queryAll();
        
        if($site_id && $id) {
            $emailModel = new EmailSystemEmail();
            $templateVar = $emailModel->getEmailListById($site_id,$id);
            $templateVar = json_decode($templateVar, true);
        }
       
        if($templateInfo && $templateVar) {
            $info = $templateInfo[0];
            $templateContent = $info['template_content'];
            $mtime = $info['last_modify'];

            // 渲染到smarty模板
            $render = new SmartyNewRenderer;
            $render->getDbResource()->setSource($templateContent);
            $render->getDbResource()->setMtime($mtime);
            $render->smarty->clearAllAssign();
            $templateVar['app'] = app();
            $render->smarty->assign($templateVar);
            $content = $render->smarty->fetch($info['uuqid'] . "-" . $info['id']);

            return $this->render('detail',[
                    'site' => $site,
                    'template_content' => $content,
                ]);
        }
    }
    
    /**
	 * 邮件详情
	 * 
	 */
    public function actionNewTemplateDetail()
    {

        $method = strtolower(Yii::$app->request->getMethod());

        $requestData = Yii::$app->request->$method();
        $site = isset( $requestData['site']) ? $requestData['site'] : '';
        $template_id = isset( $requestData['tid']) ? $requestData['tid'] : 0;
        $id = isset( $requestData['id']) ? intval($requestData['id']) : 0;
//        $templateVar = isset( $requestData['tvar']) ? json_decode(urldecode($requestData['tvar']), true) : '';
        $site_id = isset( $requestData['site_id']) ? $requestData['site_id'] : 0;
        $template_identify = isset( $requestData['identify']) ? $requestData['identify'] : 0;
        $lang = isset( $requestData['lang']) ? trim($requestData['lang']) : '';
        
        if ($site_id && $id && $template_id && $lang) {
            
            $emailModel = new EmailSystemEmail();
            $templateVar = $emailModel->getEmailListById($site_id,$id);
            $templateVar = json_decode($templateVar, true);
            
            $model = new \app\models\TemplateNew;
            $templateInfo = $model->getTemplateByLang($template_id, $lang);
            // 渲染到smarty模板
//            $modifyTime = $templateInfo['update_time'] ? $templateInfo['update_time'] : ($templateInfo['add_time'] ? $templateInfo['add_time'] : '');
            
            
            $render = new SmartyNewRenderer;
//            $render->getDbResource()->setSource($templateInfo['template_content']);
//            $render->getDbResource()->setMtime($modifyTime);
            $render->smarty->clearAllAssign();
            
            $render->smarty->assign($templateVar);
//            $render->smarty->force_compile = true;
            
            $content = $render->smarty->fetch('eval:'.$templateInfo['template_content']);
            
//            $render->getDbResource()->setSource($content);
            
            $content = $render->smarty->fetch('eval:'.$content);
            
            return $this->render('detail',[
                    'site' => $site,
                    'template_content' => $content,
                ]);
        }

    }
    
    /**
     * 记录系统邮件的打开记录
     * 记录打开邮件到mongodb
     * @return string
     */
    public function actionOpen()
    {
        $method = yii::$app->request->getMethod();

        //获取站点id
        $siteId = yii::$app->request->$method('site_id');
        $siteId = $siteId ? intval($siteId) : 0;

        //获取发送记录ID
        $id = yii::$app->request->$method("id");
        $id = $id ? intval($id) : 0;


        try {

            if (!$siteId || !$id) {
                $msg = 'parameters do not exist! params: siteId:' . $siteId . ';id:' . $id . ';';
                Elog::logCrontab($msg, 'actionOpen', 'info');

                throw new \Exception('参数不存在! params: siteId:' . $siteId . ';id:' . $id . ';');
            }

            $siteName = isset(Yii::$app->params['sites']['sys_email']['web_index'][$siteId]) ? Yii::$app->params['sites']['sys_email']['web_index'][$siteId] : '';
            
            if(!$siteName) {
                Elog::logCrontab('网站名称不存在！params: siteId:' . $siteId . ';id:' . $id . ';', 'actionOpen', 'info');
                throw new \Exception('网站名称不存在！params: siteId:' . $siteId . ';id:' . $id . ';', 'actionOpen');
            }
            
            // 获取打开设备信息
            $agent = yii::$app->request->getUserAgent();
//        var_dump($agent);
            // 设备类型 0：other 1：ios 2：android 3：pc
            if (stripos($agent, "iPhone") !== false || stripos($agent, "iPad") !== false) {
                $open_terminal = 1;
            } else if (stripos($agent, "Android") !== false) {
                $open_terminal = 2;
            } else if (stripos($agent, "Windows") !== false || stripos($agent, "mac") !== false) {
                $open_terminal = 3;
            } else {
                $open_terminal = 0;
            }

            $sql = "insert into email_".$siteName."_open_record (open_terminal,open_time,open_count,email_id) value ({$open_terminal},".time().",1,{$id}) on duplicate key update open_count = open_count + 1,is_sync = 0";

            Yii::$app->db->createCommand($sql)->execute();
        } catch (\Exception $e) {
            Elog::logCrontab($e->getMessage(), 'actionOpen', 'exception');
        }
        return;
    }
    

}
